package com.zretc.admin.service.impl;

import com.zretc.admin.dao.AdminMapper;
import com.zretc.admin.service.AdminService;
import com.zretc.api.pojo.Activity;
import com.zretc.api.pojo.SysUser;
import com.zretc.api.pojo.adminModule.Announcement;
import com.zretc.api.pojo.MessageEvent;
import com.zretc.api.pojo.recommendModule.Recommend;
import com.zretc.common.constant.WebConstant;
import com.zretc.common.entity.Pager;
import com.zretc.common.entity.R;
import com.zretc.common.entity.RespResult;
import com.zretc.redis.service.RedisService;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdminServiceimpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public MessageEvent buildEvent(String action,int userId){
        MessageEvent messageEvent = new MessageEvent();
        messageEvent.setUserId(userId);
        messageEvent.setAction(action);
        messageEvent.setTimestamp(System.currentTimeMillis());
        return messageEvent;
    }

    @Override
    @Transactional
    public RespResult approvalRecommend(Integer recommendId, Integer status)  {
        if(status !=1&&status !=2){
            return R.fail(WebConstant.APPROVAL_ERROR_CODE,WebConstant.ERROR_501);
        }
        if(adminMapper.approvalRecommend(recommendId,status)){
            if(status == 1){
                int userid =adminMapper.getUserIdByRecommendId(recommendId);
                MessageEvent messageEvent=buildEvent("addRecommendPoints",userid);
                rocketMQTemplate.convertAndSend("addPointsTopic",messageEvent);
                redisService.deleteCacheWithPrefix("recommend");
                return R.success("博文审批通过");
            }
            else {
                return R.success("博文审批不通过");
            }
        }
       return R.fail(WebConstant.APPROVAL_ERROR_CODE2,WebConstant.ERROR_502);

    }
    @Override
    public RespResult deleteRecommend(Integer recommendId) {
        if(adminMapper.deleteRecommend(recommendId)){
            redisService.deleteCacheWithPrefix("recommend");
            return R.success("删除成功");
        }
       return R.fail(WebConstant.DELETE_ERROR_CODE,WebConstant.ERROR_503);

    }

    @Override
    @Transactional
    public RespResult approvalActivity(Integer activityId, Integer status) {
        if(status !=1&&status !=2){
            return R.fail(WebConstant.APPROVAL_ERROR_CODE,WebConstant.ERROR_501);
        }
        if(adminMapper.approvalRecommend(activityId,status)){
            if(status == 1){
                int userid =adminMapper.getUserIdByActivityId(activityId);
                MessageEvent messageEvent = buildEvent("addActivityPoints",userid);
                rocketMQTemplate.convertAndSend("addPointsTopic",messageEvent);
                redisService.deleteCacheWithPrefix("activity");
                return R.success("活动审批通过");
            }
            else {
                return R.success("活动审批不通过");
            }
        }
        return R.fail(WebConstant.APPROVAL_ERROR_CODE2,WebConstant.ERROR_502);
    }

    @Override
    public RespResult deleteActivity(Integer activityId) {
        if(adminMapper.deleteActivity(activityId)){
            redisService.deleteCacheWithPrefix("activity");
            return R.success("活动删除成功");
        }
        return R.fail(WebConstant.DELETE_ERROR_CODE,WebConstant.ERROR_503);
    }

    @Override
    public RespResult approvalBlogId(Long blogId, Byte status) {
        //redisService.deleteCacheWithPrefix("blog");
        if(status !=1&&status !=2){
            return R.fail(WebConstant.APPROVAL_ERROR_CODE,WebConstant.ERROR_501);
        }
        if(adminMapper.approvalBlog(blogId,status)){
            if(status == 1){
                int userid =adminMapper.getUserIdByBlogId(blogId);
                MessageEvent messageEvent = buildEvent("addBlogPoints",userid);
                rocketMQTemplate.convertAndSend("addPointsTopic",messageEvent);
                redisService.deleteCacheWithPrefix("blog");
                return R.success("博文审批通过");
            }
            else {
                return R.success("博文审批不通过");
            }
        }
        return R.fail(WebConstant.APPROVAL_ERROR_CODE2,WebConstant.ERROR_502);
    }

    @Override
    public RespResult deleteBlog(Long blogId) {
        if( adminMapper.deleteBlog(blogId)){
            redisService.deleteCacheWithPrefix("blog");
            return R.success("博文删除成功");
        }
       return R.fail(WebConstant.DELETE_ERROR_CODE,WebConstant.ERROR_503);

    }

    @Override
    public Map<String, Object> getAllRecommend(Integer pageNum, Integer pageSize, Integer status) {
        String cacheKey = "recommend:" +pageNum+ ":" +pageSize+ ":" +"status:"+status;//构造键
        Map<String, Object> cachedData = redisService.getCacheMap(cacheKey);
        if (cachedData != null&&!cachedData.isEmpty()) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }
        Pager pager = new Pager(adminMapper.getRecommendCount(), pageNum, pageSize);
        ArrayList<Recommend> recommends = adminMapper.queryAllRecommendByPage(pager.getStartIndex(), pager.getPageSize(),status);
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",recommends);
        redisService.setCacheMap(cacheKey,map);
        return map;
    }

    @Override
    public Map<String, Object> getAllActivity(Integer pageNum, Integer pageSize, Integer status) {
        String cacheKey = "activity:" +pageNum+ ":" +pageSize+ ":" +"status:"+status;//构造键
        Map<String, Object> cachedData = redisService.getCacheMap(cacheKey);
        if (cachedData != null&&!cachedData.isEmpty()) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }
        Pager pager = new Pager(adminMapper.getActivityCount(), pageNum, pageSize);
        ArrayList<Activity> activity = adminMapper.queryAllActivityPage(pager.getStartIndex(), pager.getPageSize(),status);
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",activity);
        redisService.setCacheMap(cacheKey,map);
        return map;
    }

    @Override
    public Map<String, Object> getAllBlog(Integer pageNum, Integer pageSize, Integer status) {
        String cacheKey = "blog:" +pageNum+ ":" +pageSize+ ":" +"status:"+status;//构造键
        Map<String, Object> cachedData = redisService.getCacheMap(cacheKey);
        if (cachedData != null&&!cachedData.isEmpty()) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }
        Pager pager = new Pager(adminMapper.getBlogCount(), pageNum, pageSize);
        ArrayList<Activity> activity = adminMapper.queryAllBlogPage(pager.getStartIndex(), pager.getPageSize(),status);
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",activity);
        redisService.setCacheMap(cacheKey,map);
        return map;
    }

    @Override
    public String addAnnouncement(Announcement announcement) {
        adminMapper.addAnnouncement(announcement);
        redisService.deleteCacheWithPrefix("announcement");
        return  "添加公告成功";
    }

    @Override
    public String delAnnouncement(Integer announcementId) {
        adminMapper.delAnnouncement(announcementId);
        redisService.deleteCacheWithPrefix("announcement");
        return "删除公告成功";
    }

    @Override
    public Map<String, Object> getAllAnnouncement(Integer pageNum, Integer pageSize, Integer is_deleted) {
        String cacheKey = "announcement:" +pageNum+ ":" +pageSize+ ":" +" is_deleted:"+ is_deleted;//构造键
        Map<String, Object> cachedData = redisService.getCacheMap(cacheKey);
        if (cachedData != null&&!cachedData.isEmpty()) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }
        Pager pager = new Pager(adminMapper.getAnnoCount(), pageNum, pageSize);
        ArrayList<Announcement> announcement = adminMapper.queryAllAnnoPage(pager.getStartIndex(), pager.getPageSize(), is_deleted);
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",announcement);
        redisService.setCacheMap(cacheKey,map);
        return map;
    }

    //获取用户列表
    @Override
    public Map<String, Object> getAlluser(Integer pageNum, Integer pageSize, String role) {
        String cacheKey = "user:" +pageNum+ ":" +pageSize+ ":" +" role:"+ role;//构造键
        Map<String, Object> cachedData = redisService.getCacheMap(cacheKey);
        if (cachedData != null&&!cachedData.isEmpty()) {
            return cachedData; // 缓存命中，直接返回缓存数据
        }
        Pager pager = new Pager(adminMapper.getUserCount(), pageNum, pageSize);
        ArrayList<SysUser> sysUsers = adminMapper.queryAllUserPage(pager.getStartIndex(), pager.getPageSize(), role);
        HashMap<String,Object> map = new HashMap<>();
        map.put("pager",pager);
        map.put("list",sysUsers);
        redisService.setCacheMap(cacheKey,map);
        return map;
    }

    @Override
    public RespResult deleteUser(Integer userId) {
       boolean flag = adminMapper.deleteUser(userId);
       if(flag){
           redisService.deleteCacheWithPrefix("user");
           return R.success("删除成功");
       }
       return R.fail(WebConstant.DELETE_ERROR_CODE,WebConstant.ERROR_503);
    }

    @Override
    public RespResult updateUser(Integer userId, Integer role) {
        boolean flag = adminMapper.updateUser(userId, role);
        if(flag){
            return R.success("更改权限成功");
        }
        return R.fail(WebConstant.UPDATE_ERROR_CODE,"更改权限失败");
    }


}
